﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RadowCore.Models;

namespace RadowCore
{
    class PGConstructor
    {
        private List<PGNode> m_allNodes;

        internal List<PGNode> AllNodes
        {
            get { return m_allNodes; }
            set { m_allNodes = value; }
        }

        public PGConstructor()
        {
            m_allNodes = new List<PGNode>();
        }
        
        public PGNode Construct (TraceLogEntry traceLogEntry)
        {
            PGNode firstnode = null;
            m_allNodes.Clear();
            for (int idx = 0; idx < traceLogEntry.Trace.Count; idx++)
            {
                LogEntry currEnt = traceLogEntry.Trace[idx];
                PGNode newnode = new PGNode(currEnt.ActivityID, currEnt.Orginator,currEnt.Role, currEnt.CompleteTimeStamp);
                m_allNodes.Add(newnode);
                if (idx == 0)
                {
                    firstnode = newnode;
                }
                if (currEnt.Input.Count != 0)
                {
                    for (int idx1 = 0; idx1 < currEnt.Input.Count; idx1++)
                    {
                        string nodeName = currEnt.Input[idx1].Source;
                        string value = currEnt.Input[idx1].Value;
                        PGNode targetNode = FindNode(firstnode, nodeName);
                        if (targetNode != null)
                        {
                            targetNode.AddEdge(new PGEdge(newnode, value));
                        }
                    }
                }

            }
                      
            return firstnode;
        }

        private PGNode FindNode(PGNode fnode, string _name)
        {
            if (fnode.Name == _name)
            {
                return fnode;
            }
            else
            {
                if (fnode.Edges.Count == 0)
                {
                    return null;
                }
                else
                {
                    PGNode tmp = null;
                    for (int i = 0; i < fnode.Edges.Count; i++)
                    {
                        tmp = FindNode(fnode.Edges[i].TargetNode, _name);
                        if (tmp != null)
                            break;
                    }
                    return tmp;
                }
               
            }
        }


    }
}
